package com.software.myopiachildren.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.inuker.bluetooth.library.search.SearchRequest;
import com.inuker.bluetooth.library.search.SearchResult;
import com.inuker.bluetooth.library.search.response.SearchResponse;
import com.software.myopiachildren.R;
import com.software.myopiachildren.base.BaseActivity;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.software.myopiachildren.App.mBluetoothClient;

/**
 * 蓝牙设备
 *
 * @author penglei
 * @date 2020/05/22
 */
public class DeviceListActivity extends BaseActivity {

    private static final String TAG = "DeviceListActivity";

    @BindView(R.id.iv_title_left)
    ImageView mIvTitleLeft;
    @BindView(R.id.tv_title_text)
    TextView mTvTitleText;
    @BindView(R.id.tv_title_right)
    TextView mTvTitleRight;
    @BindView(R.id.lay_title_home)
    LinearLayout mLayTitleHome;

    @BindView(R.id.paired_devices)
    ListView mPairedDevices;


    private ArrayAdapter<String> mPairedDevicesArrayAdapter;
    // Return Intent extra
    public static String EXTRA_DEVICE_ADDRESS = "device_address";

    @Override
    protected int getContentViewId() {
        return R.layout.activity_devicelist;
    }

    @Override
    public void initView() {
        mTvTitleText.setText(getResources().getString(R.string.s_bluetooth_device));
        mTvTitleRight.setText(getResources().getString(R.string.s_scan_device));
        mTvTitleRight.setVisibility(View.VISIBLE);

//        setResult(Activity.RESULT_CANCELED);
        mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.item_device_name_list); // 2. 初始化适配器
        mPairedDevices.setAdapter(mPairedDevicesArrayAdapter); // 3. 装载适配器
        mPairedDevices.setOnItemClickListener(mDeviceClickListener); // 4. 设置监听

    }

    @Override
    public void initData() {

    }

    @OnClick({R.id.iv_title_left, R.id.tv_title_right})
    public void onClick(final View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.iv_title_left:
                finish();
                break;

            case R.id.tv_title_right:
                getDiscovery();
                break;
        }
    }

    /**
     * adapter item 监听
     */
    private AdapterView.OnItemClickListener mDeviceClickListener = new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {
            // Cancel discovery because it's costly and we're about to connect
            mBluetoothClient.stopSearch();

            // Get the device MAC address, which is the last 17 chars in the View
            String info = ((TextView) v).getText().toString();
            String address = info.substring(info.length() - 17);

            // Create the result Intent and include the MAC address
            Intent intent = new Intent();
            intent.putExtra(EXTRA_DEVICE_ADDRESS, address);

            // Set result and finish this Activity
            setResult(Activity.RESULT_OK, intent);
            finish();
        }
    };

    @Override
    protected void onResume() {
        Log.i(TAG, "onResume");
        super.onResume();
        getDiscovery();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mBluetoothClient.stopSearch();  // 离开页面时，关闭扫描
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    /**
     * discovery device
     * 扫描当前蓝牙设备
     */
    private void getDiscovery(){
        Log.i(TAG, "===doDiscovery");
        if (mBluetoothClient.isBleSupported()){
            Log.i(TAG, "支持BLE");
        }
        if(!mBluetoothClient.isBluetoothOpened()){
            mBluetoothClient.openBluetooth();
        }

       /* SearchRequest request = new SearchRequest.Builder()
                .searchBluetoothLeDevice(5000)      // 先扫BLE设备1次，每次5s
                .searchBluetoothClassicDevice(5000) // 再扫经典蓝牙5s
                .searchBluetoothLeDevice(5000)      // 扫BLE设备1次，每次5s
                .build();*/

        SearchRequest request = new SearchRequest.Builder()
                .searchBluetoothLeDevice(5000).build();

        mBluetoothClient.search(request, new SearchResponse() {
            @Override
            public void onSearchStarted() {
                Log.i(TAG, "Bluetooth 开始扫描");
            }

            @Override
            public void onDeviceFounded(SearchResult device) {
                // Beacon beacon = new Beacon(device.scanRecord);
                if(mPairedDevicesArrayAdapter.getCount() == 0){
                    mPairedDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
                    mPairedDevicesArrayAdapter.notifyDataSetChanged();
                }
                for(int i = 0; i < mPairedDevicesArrayAdapter.getCount(); i++){
                    if(mPairedDevicesArrayAdapter.getItem(i).contains(device.getAddress())){
                        break;
                    }
                    if(i == mPairedDevicesArrayAdapter.getCount()-1){
                        //Log.i(TAG, "Find new BlueTooth " + device.getName() + " Mac: " + device.getAddress());
                        mPairedDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
                        mPairedDevicesArrayAdapter.notifyDataSetChanged();
                    }
                }
            }

            @Override
            public void onSearchStopped() {
                Log.i(TAG, "Bluetooth 停止扫描");
            }

            @Override
            public void onSearchCanceled() {

            }
        });
    }


}
